import { ReactNode, useCallback, useEffect, useRef, useState } from "react";
import { useMainContentContext } from "@/service/general/publicStatic";
import { AddSvg, BookV1Svg, CloseSvg, DeleteSvg, InputSvg, ListIconSvg, PrePageSvg, SvgQuest, WordCountV1Svg } from "@/app/assets/CustomizeSvg";
import { SearchOutlined } from "@ant-design/icons";
import { UtilHelpers } from "@/service/general/utils/utilHelpers";
import { dict } from "@/service/general/dict";
import { DataSetModal, DateSetDetailModal, KnowledgeBaseModal } from "@/service/request/modal/dataModal";
import { ResponseDataList, ResponseDatasetData, ResponseDatasetDataDetail, ResponseModal, ResponseSingleModal } from "@/service/request/modal/responseModal";
import { createDatasetData, deleteDatasetData, detailDataset, getDataDetail, getDataList, updateDatasetData } from "@/service/request/requestApi";
import { PageInfo } from "@/service/general/modal/pageModal";
import { isLoggedIn } from "@/service/axiosManager";
import { message, Popover } from "antd";
import gfm from '@bytemd/plugin-gfm';
import breaks from '@bytemd/plugin-breaks';
import {Viewer} from "@bytemd/react";

import "./datasetdetail.css"
import { IndexsType, ShowType, TrainingType } from "@/service/general/enumType";
import { DatasetData, DatasetDataIndex, RequestDatasetData } from "@/service/request/modal/requestModal";
import uuid from "react-uuid";

type TimeoutHandle = ReturnType<typeof setTimeout>;

enum UpdataTabType {
    SEGMENTED,
    DATAINDEX
}

interface UpdataTab {
    id: string | number,
    name: string,
    type: UpdataTabType,
    icon?: ReactNode,
}

const UpdataTabs: UpdataTab[] = [{
    id: 1,
    name: "分块内容",
    type: UpdataTabType.SEGMENTED
}, {
    id: 2,
    name: "数据索引",
    type: UpdataTabType.DATAINDEX,
    icon: <BookV1Svg width={`100%`} height={`100%`} />
}]

const DatasetDetail = ({knowledgeBase, dataSetItem}: {knowledgeBase: KnowledgeBaseModal, dataSetItem: DataSetModal}) => {
    const {goBack} = useMainContentContext();
    const [initData, setInitData] = useState<boolean>(false);
    const [detailInfo, setDetailInfo] = useState<DateSetDetailModal>();
    const [dataList, setDataList] = useState<ResponseDatasetData[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [pNum, setPNum] = useState<number>(1);
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [isOption, setIsOption] = useState<boolean>(false);
    const [hasMore, setHasMore] = useState<boolean>(true);
    const [isEditData, setIsEditData] = useState<boolean>(false);
    const [editMode, setEditMode] = useState<ShowType>(ShowType.CREATE);
    const [editData, setEditData] = useState<ResponseDatasetData>();
    const timerRef = useRef<TimeoutHandle | null>(null);
    
    useEffect(() => {
        if (!initData && isLoggedIn()) {
            InitializeDatasetDetail();
        }
    }, []);

    useEffect(() => {
        return () => {
            setDataList((item) => []);
            setPNum(1);
            if (timerRef.current) clearTimeout(timerRef.current);
        };
    }, []);

    const InitializeDatasetDetail = () => {
        setInitData(true);
        if (dataSetItem && dataSetItem._id) {
            loadData();
        } else {
            goBack();
        }
    }

    const loadData = () => {
        loadMetadata();
        loadDataset(true);
    }

    const loadMetadata = () => {
        if (!dataSetItem._id) return;
        detailDataset({id: dataSetItem._id}).then((res: ResponseSingleModal<DateSetDetailModal>) => {
            if (res.code === 200 && res.success) {
                if (res.result) {
                    setDetailInfo(res.result);
                }
            }
        }).catch((err) => {
            console.log("获取详情失败\n", err);
        });
    }

    const loadDataset = useCallback((isInit: boolean = false) => {
        if (!dataSetItem._id || isLoading || !hasMore) return;
        setIsLoading(true);
        const param = {
            page: new PageInfo({
                pageNum: isInit ? 1 : pNum,
            }),
            id: dataSetItem._id,
            searchText: ""
        }
        getDataList(param).then((res: ResponseSingleModal<ResponseDataList>) => {
            if (res.code === 200 && res.success) {
                if (res.result) {
                    const result = res.result;
                    setTotal(result.total || 0);
                    if (isInit) {
                        setDataList([...(result.list || [])]);
                        setPNum(2);
                    } else {
                        setDataList((item) => [...item, ...(result.list || [])]);
                        setPNum((item) => item + 1);
                    }
                    setHasMore(param.page.getPageNum() * param.page.getPageSize() <= result.total);
                }
            } else if (res.message && res.message.length > 0) {
                message.error(res.message);
            }
            setIsLoading(false);
        }).catch((err) => {
            console.log("获取集合数据列表失败", err);
            setIsLoading(false);
        });
    }, [pNum]);

    const getViewGroup = () => {
        return `${total || 0} 组`;
    }

    const pullUpLoading = (event: React.UIEvent<HTMLDivElement>) => {
        const scrollTarget = event.currentTarget as HTMLDivElement;
        if (timerRef.current) clearTimeout(timerRef.current);

        timerRef.current = setTimeout(() => {
            const { scrollTop, scrollHeight, clientHeight } = scrollTarget;
            if (scrollTop + clientHeight >= scrollHeight / 2) {
                loadDataset();
            }
        }, 200);
    }

    const refreshData = () => {
        loadDataset(true);
    }

    const removeDataItem = (removeItem: ResponseDatasetData) => {
        if (!removeItem) return;
        if (isOption) {
            message.error("正在执行其他操作，请执行完后在尝试删除");
            return;
        }
        setIsOption(true);
        deleteDatasetData({id: removeItem._id}).then((res: ResponseModal<boolean>) => {
            if (res.code === 200 && res.success && res.result) {
                setDataList(data => [...data.filter(item => item._id !== removeItem._id)]);
                message.success("操作成功");
            } else {
                message.error(res.message || "删除失败");
            }
            setIsOption(false);
        }).catch((err) => {
            console.log("删除失败\n", err);
            setIsOption(false);
        });
    }

    return (<>
        <div className="w-full h-full text-black bg-[#F4F4F7]">
            <div className="h-full w-full bg-transparent grid grid-rows-1 grid-cols-[4fr,1fr] gap-2">
                <div className="h-full flex flex-col items-start justify-start gap-4 bg-white rounded-lg border-gray-400 shadow-sm px-6 py-8">
                    <div className="flex flex-row items-center justify-start gap-2 text-gray-800">
                        <div className="rotate-180 w-7 h-7 flex flex-row items-center justify-center hover:text-blue-600 cursor-pointer" onClick={goBack}><PrePageSvg width={`100%`} height={`100%`} /></div>
                        <div className="text-base">{knowledgeBase.name}</div>
                    </div>
                    <div className="w-full flex flex-row items-center justify-between">
                        <div className="flex flex-row w-fit items-center justify-center gap-2">
                            <div className="text-blue-500"><InputSvg /></div>
                            <div className="font-bold">{detailInfo?.name || dataSetItem.name}</div>
                        </div>
                        <div className="w-fit flex flex-row items-center justify-center gap-3">
                            <div 
                            className="px-4 py-1 hidden rounded-md border border-gray-300 cursor-pointer hover:border-blue-400 hover:bg-blue-100 hover:text-blue-500"
                            onClick={() => {}}
                            >
                                调整训练参数
                            </div>
                            <div 
                            className="px-4 py-1 rounded-md border border-gray-300 cursor-pointer hover:border-blue-400 hover:bg-blue-100 hover:text-blue-500"
                            onClick={() => {
                                setEditMode(ShowType.CREATE);
                                setEditData(undefined);
                                setIsEditData(true);
                            }}
                            >
                                插入
                            </div>
                        </div>
                    </div>
                    <div className="w-full border-b border-b-gray-200"></div>
                    <div className="w-full h-full flex flex-col items-center justify-start gap-2 overflow-hidden">
                        <div className="w-full flex flex-row items-center justify-between">
                            <div className="flex flex-row items-center justify-center gap-3">
                                <div className="flex flex-row items-center justify-center text-gray-500"><ListIconSvg /></div>
                                <div>{getViewGroup()}</div>
                            </div>
                            <div>
                                <div className="w-52 flex flex-row items-center justify-center gap-1 border border-gray-300 rounded-lg pr-1 py-1 hover:border-blue-400  shadow-[0_0_5px_rgb(96,165,250,0.1)] shadow-transparent has-[input:focus-within]:border-blue-400 has-[input:focus-within]:shadow-blue-400">
                                    <div className="flex flex-row items-center justify-center"><SearchOutlined className="icon-search" /></div>
                                    <div className="h-full w-auto flex flex-row items-center justify-center">
                                        <input 
                                        type="text" 
                                        placeholder="搜索相关数据" 
                                        className="w-full h-full border-none outline-none"
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="scrollbar-style w-full min-h-0 overflow-y-auto" onScroll={pullUpLoading}>
                            <div className="w-full h-fit flex flex-col items-center justify-center gap-2 py-3">
                            {
                                total || 0 > 0 ? 
                                        dataList.map((item, index) => (
                                            <div 
                                            key={`data_list_${item._id}_${index}`} 
                                            className={`w-full group/item flex flex-col items-start justify-center gap-2 rounded-lg border border-gray-300 px-3 py-3 cursor-pointer hover:border-blue-400 ${index % 2 ===0 ? "bg-blue-50 hover:bg-blue-100": "bg-gray-50 hover:bg-gray-100"}`}
                                            onClick={() => {
                                                setEditMode(ShowType.UPDATE);
                                                setEditData({...item});
                                                setIsEditData(true);
                                            }}
                                            >
                                                <div className="w-full flex flex-row items-center justify-between">
                                                    <div className="w-fit h-fit bg-white rounded-md py-[2px] px-2">
                                                        <span className="text-blue-500">#{item.chunkIndex}</span> ID:{item._id}
                                                    </div>
                                                    <div className="w-fit flex flex-row items-center justify-end gap-3 opacity-0 transition-opacity duration-[800ms] group-hover/item:opacity-100">
                                                        <div className="w-fit group/word flex flex-row items-center justify-center gap-2 py-[2px] px-2 border border-transparent bg-white rounded-md text-gray-500 hover:border-blue-400">
                                                            <div className="w-3 flex flex-row items-center justify-center group-hover/word:text-blue-400">
                                                                <WordCountV1Svg width={`100%`} height={`100%`} />
                                                            </div>
                                                            <div>
                                                                {item.q.length + item.a.length}
                                                            </div>
                                                        </div>
                                                        <div className="w-fit h-full flex flex-row items-center justify-center">
                                                            <div 
                                                            className={`w-6 p-1 flex flex-row items-center justify-center rounded-md border border-transparent bg-white text-red-500 ${isOption ? "cursor-not-allowed": ""} hover:border-red-400`}
                                                            onClick={(e) => {e.stopPropagation();removeDataItem(item)}}
                                                            >
                                                                <DeleteSvg width={`100%`} height={`100%`}/>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className="w-full flex flex-col items-start justify-center gap-4">
                                                    <div className={`bytemd w-full ${item.q ? "": "hidden"} h-fit`}>
                                                        <Viewer value={item.q} plugins={[gfm(), breaks()]}></Viewer>
                                                    </div>
                                                    <div className={`w-full ${item.q && item.a ? "": "hidden"} border-b border-b-gray-400/20 group-hover/item:border-b-transparent`}></div>
                                                    <div className={`bytemd w-full ${item.a ? "": "hidden"} h-fit`}>
                                                        <Viewer value={item.a} plugins={[gfm(), breaks()]}></Viewer>
                                                    </div>
                                                </div>
                                            </div>
                                        )):(<>
                                    <div className="w-full flex flex-col items-center justify-center">暂无数据</div>
                                    </>)
                            }
                            </div>
                        </div>
                    </div>
                </div>
                <div className="scrollbar-style h-full min-h-0 bg-white rounded-lg border-gray-400 shadow-sm p-6 overflow-y-auto">
                    <div className="w-full h-fit flex flex-col items-start justify-start gap-3 text-gray-500">
                        <div>元数据</div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">集合ID: </div>
                            <div className="flex-[7]">{detailInfo?._id || dataSetItem._id}</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">数据来源: </div>
                            <div className="flex-[7]">-</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">来源名: </div>
                            <div className="flex-[7]">{detailInfo?.sourceName}</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">来源大小: </div>
                            <div className="flex-[7]">-</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">创建时间: </div>
                            <div className="flex-[7]">{UtilHelpers.dateFormat(detailInfo?.createTime, 'YYYY-MM-DD HH:mm') || "-"}</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">更新时间: </div>
                            <div className="flex-[7]">{UtilHelpers.dateFormat(detailInfo?.updateTime, 'YYYY-MM-DD HH:mm') || "-"}</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">原文长度: </div>
                            <div className="flex-[7]">{detailInfo?.rawTextLength || "-"}</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">训练模式: </div>
                            <div className="flex-[7]">{dict.TrainingType[detailInfo?.trainingType || "-"]}</div>
                        </div>
                        <div className="w-full flex flex-row items-center justify-center">
                            <div className="flex-[2]">分割大小: </div>
                            <div className="flex-[7]">{detailInfo?.chunkSize || "-"}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {
            isEditData ? (<>
                <UpdataData title={detailInfo?.name || dataSetItem.name || ""} open={isEditData} dataset={detailInfo} dataItem={editData} mode={editMode} closeFun={setIsEditData} callback={refreshData} />
            </>):(<></>)
        }
    </>);
}

const UpdataData = ({
    title,
    mode,
    open,
    dataset,
    dataItem,
    closeFun,
    callback,
}: {
    title: string,
    mode: ShowType,
    open: boolean
    dataset?: DateSetDetailModal,
    dataItem?: ResponseDatasetData,
    closeFun: (bool: boolean) => void,
    callback?: (param?: any) => void,
}) => {
    const [isInit, setIsInit] = useState<boolean>(false);
    const [activeTab, setActiveTab] = useState<UpdataTab>(UpdataTabs[0]);
    const [isSubmit, setIsSubmit] = useState<boolean>(false);
    const [newIndexs, setNewIndexs] = useState<string[]>([]);
    const [param, setParam] = useState<DatasetData>({
        dataId: "",
        q: "",
        a: "",
        indexes: []
    });

    const indexsRefs = useRef<Record<string, HTMLTextAreaElement>>({});
    const qRef = useRef<HTMLTextAreaElement | null>(null);
    const aRef = useRef<HTMLTextAreaElement | null>(null);
    const questionMaxSize = 3000;
    const answerMaxSize = 4500;
    
    
    useEffect(() => {
        if (open) {
            Initialize();
        } else {
            setNewIndexs([]);
            setParam({
                dataId: "",
                q: "",
                a: "",
                indexes: []
            });
        }
    }, [open]);

    const Initialize = () => {
        if (isInit) return;
        setIsInit(true);
        loadData();
    }

    const loadData = () => {
        loadIndexData();
    }

    const loadIndexData = () => {
        if (mode === ShowType.CREATE) {
            if (!dataset || !dataset._id) {
                closeWindow();
                return;
            }
        } else if (mode === ShowType.UPDATE) {
            if (!dataItem || !dataItem._id) {
                closeWindow();
                return;
            }
            loadUpdataData();
        }
    }

    const loadUpdataData = () => {
        if (!dataItem?._id) return;
        const gParam  = {
            id: dataItem._id,
        }
        getDataDetail(gParam).then((res: ResponseSingleModal<ResponseDatasetDataDetail>) => {
            if (res.code === 200 && res.success) {
                const result = res.result;
                if (result && result.id) {
                    const indexes:DatasetDataIndex[] = result.indexes && result.indexes.length > 0 ? [...result.indexes.map(item => {
                        return {
                            dataId: item.dataId,
                            type: item.defaultIndex ? IndexsType.DEFAULT : IndexsType.CUSTOM,
                            text: item.text,
                            _id: item._id,
                        }
                    })]:[];
                    setParam({
                        dataId: result.id,
                        q: result.q || "",
                        a: result.a || "",
                        indexes: [...indexes]
                    });
                    return;
                }
            } else if (res.message && res.message.length > 0) {
                message.error(res.message);
            }
            closeWindow();
        }).catch((err) => {
            console.log("获取集合数据详情失败\n", err);
        });
    }

    const handleChange = (e:React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
        const {name, value} = e.currentTarget || e.target;
        changeParam({key: name, value});
    }

    const changeParam = ({key, value}: {key: string, value: any}) => {
        if (isValidKey(param, key)) {
            setParam(item => {
                return {
                    ...item,
                    [key]: value
                };
            });
        }
    }

    const updateIndexs = (updateItem: DatasetDataIndex) => {
        const key = "indexes";
        const indexs = [...param.indexes.map(item => item._id === updateItem._id ? updateItem : item)]
        changeParam({key, value: indexs});
    }
    
    const addIndexs = () => {
        const key = "indexes";
        const defaultIndex: DatasetDataIndex = {
            _id: uuid(),
            type: IndexsType.CUSTOM,
            text: "",
        }
        setNewIndexs(item => defaultIndex._id ? [...item, defaultIndex._id]:[...item]);
        const indexs = [...param.indexes, {...defaultIndex}];
        changeParam({key, value: indexs});
    }

    const deleteIndexs = (deleteItem: DatasetDataIndex) => {
        const key = "indexes";
        const indexs = [...param.indexes.filter(item => item._id !== deleteItem._id)];
        setNewIndexs(item => [...item.filter(id => id !== deleteItem._id)]);
        changeParam({key, value: indexs});
    }

    const isValidKey = <T extends Object>(obj: T, key: string | number | symbol): key is keyof T => {
        return Object.prototype.hasOwnProperty.call(obj, key);
    }

    const adjustHeight = useCallback((e: HTMLTextAreaElement) => {
        requestAnimationFrame(() => {
            e.style.height = "auto";
            e.style.height = `${e.scrollHeight}px`;
        });
    }, []);

    const closeWindow = () => {
        closeFun(false);
    }

    const isTab = (item: UpdataTab, type?: UpdataTabType) => {
        if (!type) type = UpdataTabType.DATAINDEX;

        return item.type === type;
    }

    const switchTab = (item: UpdataTab) => {
        setActiveTab({...item});
    }

    const verifySegmented = () => {
        if (!param.q) {
            if (activeTab.type !== UpdataTabType.SEGMENTED) {
                message.error("主要内容不能为空");
                setActiveTab({...UpdataTabs[0]});
            }
            qRef.current?.focus();
            return false;
        }
        return true;
    }

    const verifyDataIndex = () => {
        const emptyList = param.indexes.filter(item => !item.text);
        if (emptyList.length > 0) {
            if (activeTab.type !== UpdataTabType.DATAINDEX) {
                message.error("有索引为空，再次点击 【确认导入】 定位索引");
                setActiveTab({...UpdataTabs[1]});
            }
            emptyList[0].dataId && indexsRefs.current[emptyList[0].dataId]?.focus();
            return false;
        }
        return true;
    }

    const verifyParam = () =>{
        return activeTab.type === UpdataTabType.DATAINDEX ? verifyDataIndex() && verifySegmented() : verifySegmented() && verifyDataIndex();
    }

    const submitData = () => {
        if (isSubmit || !verifyParam()) return;
        setIsSubmit(true);
        if (mode === ShowType.CREATE) {
            createSubmit();
        } else if (mode === ShowType.UPDATE) {
            updateSubmit();
        }
    }

    const processingParam = (proData: DatasetData) => {
        const result: DatasetData = {
            ...proData,
            indexes: [...proData.indexes.filter(item => item.type !== IndexsType.DEFAULT).map(item => {
                if (item._id && newIndexs.includes(item._id)) {
                    return {
                        type: item.type,
                        text: item.text
                    }
                }
                return {
                    dataId: item.dataId,
                    type: item.type,
                    text: item.text
                }
            })],
        }
        return result;
    }

    const createSubmit = () => {
        const pParam = processingParam({...param});
        const cParam: RequestDatasetData = {
            collectionId: dataset?._id || "",
            trainingType: dataset?.trainingType || TrainingType.CHUNK,
            data: [{...pParam}]
        }
        createDatasetData({param: cParam}).then((res: ResponseModal<boolean>) => {
            if (res.code === 200 && res.success && res.result) {
                message.success("添加成功");
                if (callback) {
                    callback();
                }
                closeWindow();
            }
            setIsSubmit(false);
        }).catch((err) => {
            console.log("添加失败: \n", err);
            setIsSubmit(false);
        });
    }

    const updateSubmit = () => {
        const pParam = processingParam({...param});
        updateDatasetData({param: pParam}).then((res: ResponseModal<boolean>) => {
            if (res.code === 200 && res.success && res.result) {
                message.success("修改成功");
                if (callback) {
                    callback();
                }
                closeWindow();
            }
            setIsSubmit(false);
        }).catch((err) => {
            console.log("修改失败: \n", err);
            setIsSubmit(false);
        });
    }

    return (<>
        <div className="fixed w-full h-full top-0 left-0 flex flex-row items-center justify-center bg-black/10 text-black">
            <div className="w-1/2 h-3/4 flex flex-col items-center justify-start bg-white rounded-xl border border-gray-200">
                <div className="w-full flex flex-row items-center justify-between rounded-ss-xl rounded-se-xl bg-gray-100 py-4 px-6">
                    <div className="flex flex-row items-center justify-center gap-2 select-none">
                        <div className="text-blue-500"><InputSvg /></div>
                        <div className="font-bold">{title}</div>
                    </div>
                    <div 
                    className="w-8 h-8 p-1 transition-all duration-300 text-gray-600 hover:rotate-90 hover:bg-gray-300 rounded-lg cursor-pointer"
                    onClick={closeWindow}
                    >
                        <CloseSvg width={`100%`} height={`100%`} />
                    </div>
                </div>
                <div className="w-full min-h-0 flex-auto flex flex-col items-center justify-center gap-2 py-4 px-6 overflow-hidden">
                    <div className="w-full flex flex-row items-center justify-between">
                        <div className="flex flex-row items-center justify-center gap-4">
                            {
                                UpdataTabs.map((item, index) => (<>
                                    <div 
                                    key={`update_tab_${item.id}_${index}`} 
                                    className={`flex flex-row items-center justify-center gap-1 px-2 py-1 cursor-pointer select-none border-b-2  ${activeTab.id === item.id ? "border-b-blue-400":"border-b-transparent"}`}
                                    onClick={() => {switchTab(item)}}
                                    >
                                        <div>{item.name}</div>
                                        <div className={`${isTab(item) ? "" : "hidden"}`}>({param.indexes.length || 0})</div>
                                        <div className={`${item.icon ? "" : "hidden"} w-4 flex flex-row items-center justify-center`}>
                                            {item.icon}
                                        </div>
                                    </div>
                                </>))
                            }
                        </div>
                        {
                            isTab(activeTab) ? (<>
                                <div 
                                className="flex flex-row items-center justify-center gap-2 px-3 py-1 cursor-pointer shadow-[0_0_5px] shadow-transparent border border-gray-300 rounded-lg select-none hover:bg-blue-400 hover:text-white hover:border-blue-300 hover:shadow-blue-200"
                                onClick={addIndexs}
                                >
                                    <div className="w-3 flex flex-row items-center justify-center">
                                        <AddSvg width={`100%`} height={`100%`} />
                                    </div>
                                    <div>新增</div>
                                </div>
                            </>):(<></>)
                        }
                    </div>
                    <div className="scrollbar-style w-full min-h-0 h-5/6 flex flex-row items-center justify-center px-3 py-2 overflow-y-auto">
                        {
                            activeTab.type === UpdataTabType.SEGMENTED ? (<>
                                <div className="w-full h-full flex flex-row items-center justify-center gap-4">
                                    <div className="h-full flex-1 flex flex-col items-start justify-start gap-2">
                                        <div className="flex flex-row items-center justify-center gap-1">
                                            <div><span className="text-red-600">*</span>主要内容</div>
                                            <Popover content={<>
                                                    <div>该输入框是必填项<br />该内容通常是对于知识点的描述，也可以是用户的问题</div>
                                                </>} trigger="hover" placement="bottom">
                                            <div className="w-4 flex flex-row items-center justify-center cursor-pointer"><SvgQuest width={`100%`} height={`100%`} /></div>
                                            </Popover>
                                        </div>
                                        <div className="w-full flex-1 flex flex-col items-center justify-center">
                                            <div 
                                            className="w-full h-full min-h-24 flex-1 flex flex-row items-center justify-center p-3 border border-gray-200 shadow-[0_0_5px]  shadow-transparent rounded-lg hover:border-blue-300 has-[textarea:focus-within]:border-blue-400 has-[textarea:focus-within]:shadow-blue-500"
                                            >
                                                <textarea 
                                                ref={qRef}
                                                name="q"
                                                value={param.q}
                                                placeholder={`该输入框是必填项，该内容通常是对于知识点的描述，也可以是用户的问题，最多 ${questionMaxSize} 字。`} 
                                                maxLength={questionMaxSize} 
                                                className="scrollbar-style border-none outline-none bg-transparent w-full h-full resize-none"
                                                onChange={handleChange}
                                                ></textarea>
                                            </div>
                                            <div className="w-full flex flex-row items-center justify-end">
                                                <div className="text-gray-400">{param.q.length} / {questionMaxSize}</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div className="h-full flex-1 flex flex-col items-start justify-start gap-2">
                                        <div className="flex flex-row items-center justify-center gap-1">
                                            <div>辅助数据</div>
                                            <Popover content={<>
                                                    <div>该部分为可选填项<br />通常是为了与前面的数据内容配合，构建结构化提示词，用于特殊场景</div>
                                                </>} trigger="hover" placement="bottom">
                                            <div className="w-4 flex flex-row items-center justify-center cursor-pointer"><SvgQuest width={`100%`} height={`100%`} /></div>
                                            </Popover>
                                        </div>
                                        <div className="w-full flex-1 flex flex-col items-center justify-center">
                                            <div 
                                            className="w-full h-full min-h-24 flex-1 flex flex-row items-center justify-center p-3 border border-gray-200 rounded-lg hover:border-blue-300 has-[textarea:focus-within]:border-blue-400 has-[textarea:focus-within]:shadow-blue-500"
                                            >
                                                <textarea 
                                                ref={aRef}
                                                name="a"
                                                value={param.a}
                                                placeholder={`该部分为可选填项，通常是为了与前面的【数据内容】配合，构建结构化提示词，用于特殊场景，最多 ${answerMaxSize} 字。`} 
                                                maxLength={answerMaxSize} 
                                                className="scrollbar-style border-none outline-none bg-transparent w-full h-full resize-none"
                                                onChange={handleChange}
                                                ></textarea>
                                            </div>
                                            <div className="w-full flex flex-row items-center justify-end">
                                                <div className="text-gray-400">{param.a.length} / {answerMaxSize}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </>):(<>
                                <div className="w-full h-full flex flex-col items-center justify-start gap-3">
                                    {
                                        (param.indexes.length || 0) > 0 && mode !== ShowType.CREATE ? (<></>):(<>
                                            <div className="w-full flex flex-col items-start justify-center gap-3 p-4 rounded-lg border border-blue-100 bg-blue-50">
                                                <div className="text-blue-600">默认索引</div>
                                                <div>无法编辑，默认索引会使用【相关数据内容】与【辅助数据】的文本直接生成索引。</div>
                                            </div>
                                        </>)
                                    }
                                    {
                                        param.indexes.map((item,index) =>
                                            {
                                                return item.type === IndexsType.DEFAULT ? (<>
                                                    <div key={`index_${item.type}_${item._id}_${item.dataId}_${index}`} className="w-full flex flex-col items-start justify-center gap-3 p-4 rounded-lg border border-blue-100 bg-blue-50">
                                                        <div className="text-blue-600">默认索引</div>
                                                        <div>无法编辑，默认索引会使用【相关数据内容】与【辅助数据】的文本直接生成索引。</div>
                                                    </div>
                                                </>):(<>
                                                    <div key={`index_${item.type}_${item._id}_${item.dataId}_${index}`} className="w-full flex flex-col items-start justify-center gap-3 p-4 rounded-lg border border-gray-100 bg-gray-50">
                                                        <div className="w-full flex flex-row items-center justify-between">
                                                            <div>自定义索引{index}</div>
                                                            <div 
                                                            className="w-3 flex flex-row items-center justify-center cursor-pointer text-gray-500 hover:text-red-600"
                                                            onClick={() => deleteIndexs(item)}
                                                            >
                                                                <DeleteSvg width={`100%`} height={`100%`} />
                                                            </div>
                                                        </div>
                                                        <div className="w-full h-fit">
                                                            <div className="w-full min-h-11 h-fit flex flex-row items-center justify-center px-2 py-1 rounded-lg border border-transparent shadow-[0_0_5px] shadow-transparent hover:border-blue-400 has-[textarea:focus-within]:border-blue-400 has-[textarea:focus-within]:shadow-blue-400">
                                                                <textarea 
                                                                ref={el => {
                                                                    item._id && (el ? indexsRefs.current[item._id] = el : delete indexsRefs.current[item._id]);
                                                                }}
                                                                value={item.text}
                                                                placeholder="请输入索引文本内容"
                                                                className="w-full h-fit min-h-full bg-transparent outline-none border-none resize-none overflow-hidden"
                                                                onChange={(e) => {
                                                                    const {value} = e.currentTarget || e.target;
                                                                    const uItem:DatasetDataIndex = {
                                                                        ...item,
                                                                        text: value
                                                                    }
                                                                    updateIndexs(uItem);
                                                                    adjustHeight(e.currentTarget || e.target);
                                                                }}
                                                                onInput={(e) => {adjustHeight(e.currentTarget || e.target)}}
                                                                ></textarea>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </>)
                                            })
                                    }
                                </div>
                            </>)
                        }
                    </div>
                    <div className="w-full flex flex-row items-center justify-end">
                        <div 
                        className="flex flex-row items-center justify-center px-4 py-2 bg-blue-600 text-white rounded-lg cursor-pointer hover:bg-blue-600/80"
                        onClick={submitData}
                        >
                            确认导入
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </>);
}

export {
    DatasetDetail
}